"use strict"
const http = require('http');
const https = require('https');
const crypto = require('crypto');
//接入taptap sdk
//登录
exports.format = {
    "id": 'taptap',
    "name": "taptap",
    "fields": {
        client_id: { 'type': 'string', 'val': 'y0epbnwb8xshsmxkip', "name": "client_id" },
        client_token: { 'type': 'string', 'val': '9pRAGs673lsCZ0R6hUEJRSbdPuuiucTUecga871k', "name": "client_token" },
        test_client_id: { 'type': 'string', 'val': '41uhej1hljwkxoxduk', "name": "test_client_id" },
        test_client_token: { 'type': 'string', 'val': 'Zfew0TTb0s0WqicM07TbTwOYlYZZ8Yad5HmxVUsd', "name": "test_client_token" },
        // secret: { 'type': 'string', 'val': 'mBFFzYAnucaeoGkE7kjpfebRPD4aWkpr', "name": "secret" },
        secret: { 'type': 'string', 'val': 'nRdGQau4Ze11L8ARKNJ6egmZdYkJpm2u', "name": "secret" },
    }
}

// const client_id = "41uhej1hljwkxoxduk";
const client_id = "y0epbnwb8xshsmxkip";
const requestUrl = 'https://open.tapapis.cn/account/profile/v1?client_id=' + client_id;
const method = 'GET';


function getAuthorization(requestUrl, method, keyId, macKey) {
    const url = new URL(requestUrl);
    const time = Math.floor(Date.now() / 1000).toString().padStart(10, '0');
    const randomStr = getRandomString(16);
    const host = url.hostname;
    const uri = url.pathname + url.search;
    const port = url.port || (url.protocol === 'https:' ? '443' : '80');
    const other = '';
    const sign = signData(mergeData(time, randomStr, method, uri, host, port, other), macKey);
    return `MAC id="${keyId}", ts="${time}", nonce="${randomStr}", mac="${sign}"`;
}

function getRandomString(length) {
    return crypto.randomBytes(length).toString('base64');
}

function mergeData(time, randomCode, httpType, uri, domain, port, other) {
    let prefix =
        `${time}\n${randomCode}\n${httpType}\n${uri}\n${domain}\n${port}\n`;

    if (!other) {
        prefix += '\n';
    } else {
        prefix += `${other}\n`;
    }

    return prefix;
}

function signData(signatureBaseString, key) {
    const hmac = crypto.createHmac('sha1', key);
    hmac.update(signatureBaseString);
    return hmac.digest('base64');
}


/**
 * @name login
 */

exports.login = async function () {
    let keyId = this.get("keyId", "string");
    if (!keyId) {
        return this.error("token empty");
    }
    let macKey = this.get("macKey", "string");
    if (!macKey) {
        return this.error("macKey empty");
    }
    // let args = JSON.parse(token);
    // console.log('args:', args);
    console.log('keyId:', keyId);
    console.log('macKey:', macKey);
    const authorization = getAuthorization(requestUrl, method, keyId, macKey);
    const options = new URL(requestUrl);
    try {
        const data = await makeRequest(options, authorization);
        console.log(data); // 处理数据
        let ret = JSON.parse(data);
        return ret.data.openid;
    } catch (error) {
        console.error(error); // 处理错误
    }
}
function makeRequest(options, authorization) {
    const client = options.protocol === 'https:' ? https : http;
    return new Promise((resolve, reject) => {
        const req = client.request({
            hostname: options.hostname,
            port: options.port,
            path: options.pathname + options.search,
            method: 'GET',
            headers: {
                'Authorization': authorization
            }
        }, (res) => {
            let data = '';

            res.on('data', (chunk) => {
                data += chunk;
            });

            res.on('end', () => {
                resolve(data); // 当数据接收完毕，解决 Promise
            });
        });

        req.on('error', (error) => {
            reject(error); // 如果请求失败，拒绝 Promise
        });

        req.end();
    });
}